﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using System.Linq;
using System.Security.Claims;

namespace RayD.Core 
{ 
    /// <summary>
    /// Json Web Token 帮助类
    /// </summary>
    public static class JwtHelper
    {
        /// <summary>
        /// 颁发JWT字符串
        /// </summary>
        /// <param name="claimDict">声明字典</param>
        /// <returns></returns>
        public static string BuildJwtToken(Dictionary<string, string> claimDict)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.Jwt.SigningKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: AppSettings.Jwt.Issuer,
                audience: AppSettings.Jwt.Audience,
                claims: claimDict.Select(x => new Claim(x.Key, x.Value)),
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddMinutes(AppSettings.Jwt.ExpireTime),
                signingCredentials: creds);
            var jwt = new JwtSecurityTokenHandler().WriteToken(token);

            return jwt;
        }
        /// <summary>
        /// 解析JWT
        /// </summary>
        /// <param name="jwt">JWT字符串</param>
        /// <returns></returns>
        public static Dictionary<string, string> SerializeJwt(string jwt)
        {
            var token = new JwtSecurityTokenHandler().ReadJwtToken(jwt);
            Dictionary<string, string> dict = new Dictionary<string, string>();
            if (token.Claims != null)
            {
                foreach (var claim in token.Claims)
                {
                    dict.Add(claim.Type, claim.Value);
                }
            }
            //return (dict, token.ValidTo);
            return dict;
        }
    }
}
